package com.vcc.service.sa;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.exception.SignInException;
import com.vcc.data.entity.BossRole;
import com.vcc.data.entity.BossUser;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

public class BossUserUtil {

    private static final String CUSTOMER_SESSION_KEY = "BOSS_USER";

    public static void set(BossUser customer, BossRole role) {
        JSONObject map = new JSONObject();
        map.put("id", customer.getId());
        map.put("roleId", role.getId());
        map.put("user", customer);
        map.put("role", role);
        StpUtil.getSession().set(CUSTOMER_SESSION_KEY, map);
    }

    public static BossUser get() {
        JSONObject map = (JSONObject) StpUtil.getSession().get(CUSTOMER_SESSION_KEY);
        if (map == null) {
            throw new SignInException("用户未登录");
        }
       BossUser bossUser = (BossUser) map.get("user");
        if (bossUser == null) {
            throw new SignInException("用户未登录");
        }
        return bossUser;
    }

    public static BossRole getRole() {
        JSONObject map = (JSONObject) StpUtil.getSession().get(CUSTOMER_SESSION_KEY);
        if (map == null) {
            throw new SignInException("用户未登录");
        }
        BossRole role = (BossRole) map.get("role");
        if (role == null) {
            throw new SignInException("用户未登录");
        }
        return role;
    }

    public static Long getId() {
        JSONObject map = (JSONObject) StpUtil.getSession().get(CUSTOMER_SESSION_KEY);
        if (map == null) {
            throw new SignInException("用户未登录");
        }
        return Optional.of(map.getLongValue("id")).orElseThrow(() -> new ProgramException("用户未登录"));
    }

    public static Long getIdNotNull() {
        JSONObject map = (JSONObject) StpUtil.getSession().get(CUSTOMER_SESSION_KEY);
        if (map == null) {
            throw new SignInException("用户未登录");
        }
        return map.getLongValue("id");
    }

    public static void login(Long id, String device) {
        if (StpUtil.isDisable(id)) {
            throw new SignInException("账号被封禁");
        }
        if (StringUtils.isNotBlank(device)) {
            StpUtil.login(id, device);
        } else {
            StpUtil.login(id);
        }
    }

    public static boolean hasAllData(){
        BossRole role = getRole();
        return role.getHasAllData() != null && role.getHasAllData();
    }

    public static void logout() {
        StpUtil.logout();
    }

    public static void logout(Long loginId) {
        StpUtil.logout(loginId);
    }

    public static void openSafe(Long safeTime) {
        StpUtil.openSafe(safeTime);
    }

    public static void openSafe(String service, Long safeTime) {
        StpUtil.openSafe(service, safeTime);
    }

    public static void kickout(Long id) {
        StpUtil.kickout(id);
    }

}
